import React, { useState, useEffect, useMemo, useCallback } from "react";
import {
  Comment,
  Tooltip,
  List,
  Pagination,
  Input,
  Button,
  Space,
  message,
  Modal,
  Result,
  Empty,
  Popconfirm,
} from "antd";
import RecommendList from "./RecommendData";
import {
  DislikeOutlined,
  LikeOutlined,
  DislikeFilled,
  LikeFilled,
  DownCircleOutlined,
  ExclamationCircleOutlined,
  UpCircleOutlined,
} from "@ant-design/icons";
import BraftEditor from "braft-editor";
import "braft-editor/dist/index.css";
import moment from "moment";
import axios from "axios";
import MyIcon from "../../components/Iconfont/Index";
import Qs from "qs";
import { connect } from "react-redux";
const { TextArea } = Input;
const getContent = (comments) => {
  return { __html: comments };
};

function CommentsList({
  UpateUserInfo,
  current,
  pageSize,
  setCurrent,
  setPageSize,
  loading,
  total,
  dataList,
  getData,
}) {
  const [cid, setId] = useState(null);
  const [showText, setShowText] = useState(false);
  const [showList, setShowList] = useState([]);
  const [toreplyname, setreplyName] = useState("");
  const [toreplyId, setToreplyId] = useState(null);
  const [textareaValue, settextValue] = useState("");
  // const dataList = useMemo(async()=> {
  //   console.log(datas);
  //   return datas
  // },[])
  function onChange(page, pageSize) {
    console.log(page, pageSize);
    setCurrent((prev) => page);
    setPageSize((prev) => pageSize);
    getData(page, pageSize);
  }
  function onShowSizeChange(current, size) {
    setCurrent((prev) => 1);
    setPageSize((prev) => size);
    getData(1, size);
  }

  const changeTextarea = function (e) {
    e.persist();
    settextValue((prev) => e.target.value);
  };
  const deleteMessage =async (id, messages) => {
        let { data: res } = await axios.get("/api/delcomments", {
          params: {
            id,
            message: messages,
            userid:UpateUserInfo.userInfo.id,
          },
        });
        if (res.ok !== 1) {
          return message.error(res.message);
        }
        message.success(res.message);
        if (dataList.length == 1) {
          if (current == 1) {
            getData(current, pageSize);
            return;
          }
          getData(current - 1, pageSize);
          setCurrent((prev) => current - 1);
        } else {
          getData(current, pageSize);
        }
  };
  const agreeordisagree = async function (id, messages, isok) {
    if (!isok) {
      let { data: res } = await axios.post(
        "/api/postagree",
        Qs.stringify({
          commentsid: id,
          commentkind: messages,
          userid:UpateUserInfo.userInfo.id,
        }),
        {
          headers: {
            "Content-type": "application/x-www-form-urlencoded",
          },
        }
      );
      if (res.ok !== 1) {
        return message.error(res.message);
      }
      message.success(res.message);
      getData(current, pageSize);
    }
  };
  const submitTextArea = async function () {
    if (textareaValue.trim("") == "") {
      return message.warning("输入的内容不能只为空或空格");
    }
    let { data: res } = await axios.post(
      "/api/replycomments",
      Qs.stringify({
        replycomments: textareaValue,
        replymainid: cid,
        replytime: moment().unix(),
        personid: toreplyId,
        meid: UpateUserInfo.userInfo.id,
        userid:UpateUserInfo.userInfo.id,
      }),
      {
        headers: { "Content-type": "application/x-www-form-urlencoded" },
      }
    );
    if (res.ok !== 1) {
      return message.error(res.message);
    }
    message.success(res.message);
    settextValue((prev) => "");
    setShowText((prev) => false);
    getData(current, pageSize);
  };
  const getconfirm = async function (id, messages, isok) {
    let { data: res } = await axios.get("/api/delagree", {
      params: {
        id,
        commentkind: messages,
        userid:UpateUserInfo.userInfo.id
      },
    });
    if (res.ok !== 1) {
      return message.error(res.message);
    }
    message.success(res.message) ;
    getData(current, pageSize);
  };
  useEffect(() => {
    getData(current, pageSize);
  }, []);
  return (
    <div style={{ marginBottom: "40px" }}>
      <RecommendList></RecommendList>
      {dataList.length > 0 ? (
        <>
          <List
            className="comment-list"
            itemLayout="horizontal"
            dataSource={dataList}
            loading={loading}
            // loadMore={true}
            renderItem={(item, index) => (
              <>
                <Comment
                  key={item.id}
                  actions={[
                    <span
                      key="xxxxx"
                      onClick={() => {
                        !item.isok && agreeordisagree(item.id, "评论", item.isok);
                      }}
                    >
                      {item.isok ? (
                        <Popconfirm
                          placement="top"
                          title="确定取消对该评论的点赞吗"
                          onConfirm={() => {
                            getconfirm(item.id, "评论", item.isok);
                          }}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Tooltip title="取消点赞">
                            <MyIcon
                              type="icon-praise"
                              // style={{ color: {...item1}.isok === true ? "red" : "8c8c8c" }}
                              className="redicon"
                            ></MyIcon>{" "}
                            总赞数 &ensp;<span className="comment-action">{item.agreepoints}</span>
                          </Tooltip>
                        </Popconfirm>
                      ) : (
                        <Tooltip title="点赞">
                          <MyIcon
                            type="icon-praise"
                            // style={{ color: {...item1}.isok === true ? "red" : "8c8c8c" }}
                            className="grayicon"
                          ></MyIcon>{" "}
                          总赞数 &ensp;<span className="comment-action">{item.agreepoints}</span>
                        </Tooltip>
                      )}
                    </span>,
                    item.userid == UpateUserInfo.userInfo.id ? (
                      <span
                      >
                       <Popconfirm
                                    placement="rightTop"
                                    title={<div>
                                      删除评论可能会删除别人对于您的该评论的所有回复。
                                      <br/>
                                      确定删除吗 ?
                                    </div>}
                                    onConfirm={() => {
                                      deleteMessage(item.id, "评论");
                                    }}
                                    okText="确定"
                                    cancelText="取消"
                                  >
                                    <Tooltip title="删除">
                                  <MyIcon type="icon-lajitong" /> 删除</Tooltip></Popconfirm>
                      </span>
                    ) : null,
                    <span
                      key="comment-basic-reply-to"
                      onClick={() => {
                        settextValue((prev) => "");
                        setId((prev) => item.id);
                        setShowText((prev) => true);
                        setreplyName((prev) => item.username);
                        setToreplyId((prev) => item.userid);
                      }}
                    >
                       <Tooltip title="回复">
                      <MyIcon type="icon-huifu"></MyIcon> 回复</Tooltip>
                    </span>,
                  ]}
                  author={item.username}
                  avatar={item.img}
                  content={<div dangerouslySetInnerHTML={getContent(item.comments)}></div>}
                  datetime={
                    <>
                      <Tooltip
                        title={moment(parseInt(item.commenttime) * 1000).format(
                          "YYYY-MM-DD HH:mm:ss"
                        )}
                      >
                        <span>
                          {moment(parseInt(item.commenttime) * 1000).format("YYYY-MM-DD HH:mm:ss")}
                        </span>
                      </Tooltip>
                      &emsp;{" "}
                      <span style={{ color: "#8c8c8c" }}>
                        第 {total - (current - 1) * pageSize - index} 楼
                      </span>
                    </>
                  }
                >
                  {item.childrenlist
                    ? item.childrenlist
                        .slice(0, showList.includes(item.id) ? item.childrenlist.length : 1)
                        .map((item1, index) => (
                          <Comment
                            key={item1.id}
                            actions={[
                              <span
                                key="xxxx"
                                onClick={() => {
                                  !item1.ok && agreeordisagree(item1.id, "回复", item1.isok);
                                }}
                              >
                                {item1.isok ? (
                                  <Popconfirm
                                    placement="top"
                                    title="确定取消对该评论的点赞吗"
                                    onConfirm={() => {
                                      getconfirm(item1.id, "回复", item1.isok);
                                    }}
                                    okText="确定"
                                    cancelText="取消"
                                  >
                                    <Tooltip title="取消点赞">
                                      <MyIcon
                                        type="icon-praise"
                                        // style={{ color: {...item1}.isok === true ? "red" : "8c8c8c" }}
                                        className="redicon"
                                      ></MyIcon>{" "}
                                      总赞数 &ensp;
                                      <span className="comment-action">{item1.agreepoints}</span>
                                    </Tooltip>
                                  </Popconfirm>
                                ) : (
                                  <Tooltip title="点赞">
                                    <MyIcon
                                      type="icon-praise"
                                      // style={{ color: {...item1}.isok === true ? "red" : "8c8c8c" }}
                                      className="grayicon"
                                    ></MyIcon>{" "}
                                    总赞数 &ensp;
                                    <span className="comment-action">{item1.agreepoints}</span>
                                  </Tooltip>
                                )}
                              </span>,

                              item1.meid == UpateUserInfo.userInfo.id ? (
                                <span
                                  // onClick={() => {
                                  //  
                                  // }}
                                >
                                   <Popconfirm
                                    placement="rightTop"
                                    title={<div>
                                      删除评论可能会删除别人对于您的该评论的所有回复。
                                      <br/>
                                      确定删除吗 ?
                                    </div>}
                                    onConfirm={() => {
                                      deleteMessage(item1.id, "回复");
                                    }}
                                    okText="确定"
                                    cancelText="取消"
                                  >
                                    <Tooltip title="删除">
                                  <MyIcon type="icon-lajitong" /> 删除</Tooltip></Popconfirm>
                                </span>
                              ) : null,
                              <span
                                key="comment-basic-reply-to"
                                onClick={() => {
                                  settextValue((prev) => "");
                                  setId((prev) => item.id);
                                  setShowText((prev) => true);
                                  setreplyName((prev) => item1.username);
                                  setToreplyId((prev) => item1.meid);
                                }}
                              >
                                <Tooltip title="回复">
                      <MyIcon type="icon-huifu"></MyIcon> 回复</Tooltip>
                              </span>,
                            ]}
                            author={
                              <span>
                                {item1.username}&ensp;
                                <MyIcon type="icon-at-copy" style={{ fontSize: "1.2rem" }}></MyIcon>
                                &ensp;{item1.replyusername}
                              </span>
                            }
                            avatar={item1.img}
                            content={<div>{item1.replycomments}</div>}
                            datetime={
                              <>
                                <Tooltip
                                  title={moment(parseInt(item1.replytime) * 1000).format(
                                    "YYYY-MM-DD HH:mm:ss"
                                  )}
                                >
                                  <span>
                                    {moment(parseInt(item1.replytime) * 1000).format(
                                      "YYYY-MM-DD HH:mm:ss"
                                    )}
                                  </span>
                                </Tooltip>
                                &emsp;{" "}
                              </>
                            }
                          ></Comment>
                        ))
                    : null}
                  {item.childrenlist && item.childrenlist.length > 1 ? (
                    <div>
                      {showList.includes(item.id) ? (
                        <Button
                          type="link"
                          onClick={() => {
                            let index = showList.findIndex((itema) => itema == item.id);
                            let showli = [...showList];
                            showli.splice(index, 1);
                            setShowList(() => showli);
                          }}
                        >
                          收起共{item.childrenlist.length}条回复&ensp;
                          <UpCircleOutlined />
                        </Button>
                      ) : (
                        <Button
                          type="link"
                          onClick={() => {
                            setShowList(() => [...showList, item.id]);
                          }}
                        >
                          展开共{item.childrenlist.length}条回复&ensp;
                          <DownCircleOutlined />
                        </Button>
                      )}
                    </div>
                  ) : null}

                  {cid == item.id && showText ? (
                    <div style={{ height: "13rem", width: "70%" }}>
                      <div style={{ height: "10rem" }}>
                        <TextArea
                          onChange={changeTextarea}
                          value={textareaValue}
                          placeholder={UpateUserInfo.userInfo.username + ` @ ` + toreplyname}
                        ></TextArea>
                      </div>

                      <div style={{ textAlign: "right", marginTop: "1rem" }}>
                        {" "}
                        <Space size="middle">
                          <Button
                            type="priamry"
                            size="middle"
                            onClick={() => {
                              setShowText((prev) => false);
                              settextValue((prev) => "");
                            }}
                          >
                            取消
                          </Button>
                          <Button type="primary" size="middle" onClick={submitTextArea}>
                            回复
                          </Button>
                        </Space>
                      </div>
                    </div>
                  ) : null}
                </Comment>
              </>
            )}
          />
          <Pagination
            style={{ marginTop: "30px" }}
            showQuickJumper
            current={current}
            pageSizeOptions={["5", "10", "20", "30"]}
            pageSize={pageSize}
            defaultCurrent={1}
            total={total}
            showSizeChanger
            onChange={onChange}
            onShowSizeChange={onShowSizeChange}
          />
        </>
      ) : (
        <Empty style={{ marginTop: "40px" }} description="暂无评论" />
      )}
    </div>
  );
}

export default connect((state) => state)(CommentsList);
